package at.fhj.swd.pse.domain;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.inject.Inject;

import at.fhj.swd.pse.data.ActivityDAO;
import at.fhj.swd.pse.entities.Activity;
import at.fhj.swd.pse.entities.Community;

public final class ActivityServiceImpl implements ActivityService {

	@Inject
	private ActivityDAO a_dao;

	@Override
	public Activity createNewActivity(final Activity activity) {
		return this.a_dao.insert(activity);		
	}
	
	@Override
	public Activity createNewActivity(final Activity activity, final Community community) {
		Activity a = createNewActivity(activity);		
				
		a_dao.addToCommunity(a.getId(),	community.getID());
		
		return a;
	}

	@Override
	public void removeActivity(final Activity activity) {
		this.a_dao.remove(activity);
	}

	@Override
	public List<Activity> getAllActivities(final int userId) {
		List<Activity> activities;
		activities = this.a_dao.getGlobalActivities();
		activities.addAll(this.a_dao.getFriendActivities(userId));
		activities.addAll(this.a_dao.getAllCommunityActivities(userId));
		activities.addAll(this.a_dao.getOwnActivities(userId));
		return this.sortList(activities);
	}

	private List<Activity> sortList(final List<Activity> activities) {
		Collections.sort(activities, new Comparator<Activity>() {

			@Override
			public int compare(final Activity a1, final Activity a2) {
				if (a1.getTimestamp().before(a2.getTimestamp())) {
					return 1;
				} else if (a1.getTimestamp().after(a2.getTimestamp())) {
					return -1;
				}
				return 0;
			}

		});
		return activities;
	}

	public void setA_dao(ActivityDAO a_dao) {
		this.a_dao = a_dao;
	}
	
	

}
